package com.df.twod_sync_bakend.confg;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.df.twod_sync_bakend.game.GameRoom;
import com.df.twod_sync_bakend.game.IScript;
import com.google.gson.JsonObject;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class MyWsHandler extends TextWebSocketHandler {

    @Autowired
    private List<IScript> scripts;

    Map<String,IScript> scriptMap = new HashMap<>();
    GameRoom room = new GameRoom(1);

    @PostConstruct
    void initScripts(){
        log.info("脚本数量:"+scripts.size());
        for (IScript script : scripts) {
            scriptMap.put(script.getType(),script);
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("新连接建立: " + session.getId());
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("收到消息: " + message.getPayload());

        try {
            JSONObject jsonObject = JSON.parseObject(message.getPayload());
            String type = jsonObject.getString("type");
            if(type==null){
                throw new RuntimeException("没有消息类型，无法解析！");
            }
            IScript iScript = scriptMap.get(type);
            if(iScript==null){
                throw new RuntimeException("未定义的消息类型："+type);
            }
            Object data = iScript.unserialize(jsonObject.getJSONObject("data").toJSONString());
            iScript.handle(session,data,room);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handlePositionUpdate(WebSocketSession session, JsonObject json) throws Exception {
//        String uid = sessionPlayerMap.get(session);
//        if (uid == null) {
//            sendError(session, 2001, "未登录");
//            return;
//        }
//
//        JsonObject data = json.getAsJsonObject("data");
//        float x = data.get("x").getAsFloat();
//        float y = data.get("y").getAsFloat();
//        float direction = data.get("direction").getAsFloat();
//
//        // 获取是否移动的状态，默认为false
//        boolean isMoving = data.has("isMoving") ? data.get("isMoving").getAsBoolean() : false;
//
//        // 使用服务器权威模式处理移动请求
//        Map<String, Object> result = GameMap.getInstance().processPlayerMovement(uid, x, y, direction, isMoving);
//
//        if (result != null) {
//            boolean isValid = (boolean) result.get("isValid");
//
//            // 如果位置无效，发送校正消息给客户端
//            if (!isValid) {
//                float serverX = ((Number) result.get("serverX")).floatValue();
//                float serverY = ((Number) result.get("serverY")).floatValue();
//                GameMap.getInstance().sendPositionCorrection(uid, serverX, serverY);
//            }
//        }
    }



    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Object uid = session.getAttributes().get("uid");
        if(uid!=null){
            room.removePlayer(uid.toString());
            System.out.println("玩家离开: " + uid);
        }
        super.afterConnectionClosed(session, status);
        System.out.println("连接断开："+session.getId()+" reason:"+status.getReason());
    }
}
